package com.autumn.sms.service.services.impl;

import com.autumn.domain.entities.AbstractEntity;
import com.autumn.domain.entities.auditing.AbstractDefaultFullGmtEntity;
import com.autumn.domain.repositories.IDefaultEntityRepository;
import com.autumn.mybatis.criterion.Query;
import com.autumn.sms.service.utils.AuditUtils;
import com.autumn.validation.ValidationException;

/**
 * 抽象基本服务
 * 
 * @author JuWa ▪ Zhang
 * @date 2018年1月9日
 */
public abstract class AbstractBasicService<TRepo extends IDefaultEntityRepository<TEntity>, TEntity extends AbstractDefaultFullGmtEntity> {

	/**
	 * 获取实体仓储
	 * @return
	 */
	protected abstract TRepo getRepository();
	
	protected int getPageMaxValue() {
		return 100;
	}
	
	/**
	 * 获取实体类
	 * @return
	 */
	protected abstract Class<TEntity> getEntityClass();

	/**
	 * 通过主键ID检测该实体记录是否存在
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected TEntity checkIsExistEntityByPrimaryId(long id) {
		Query query = AuditUtils.generateQueryById(getEntityClass(), id);
		AuditUtils.filterDelete(query);
		AbstractEntity<Long> selectFirst = getRepository().selectFirst(query.builderSection());
		if (selectFirst == null) {
			throw new ValidationException(
					String.format("实体 [%s] 中主键ID为 [%s] 的记录不存在", getEntityClass().getSimpleName(), id));
		}
		return (TEntity) selectFirst;
	}
	
}
